package com.ruoyi.business.service.impl;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.mapper.UserMapper;
import com.ruoyi.business.service.IUserServer;
import com.ruoyi.common.core.domain.entity.UserInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ip.IpUtils;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;

@Service
public class UserServerImpl extends ServiceImpl<UserMapper, UserInfo> implements IUserServer{
	@Autowired 
	private UserMapper mapper;
	private static final Logger log = LoggerFactory.getLogger(UserServerImpl.class);
	@Autowired
	private RedisCache redisCache;

	@Override
	public UserInfo signup(String phone,String password,String code,String qq) {
		//TODO 需要短信验证，现在暂时不验证 
		//查询手机号码是否重复
		UserInfo userinfo = new LambdaQueryChainWrapper<>(mapper)
				.eq(UserInfo::getPhone, phone)
				.one();

		if(ObjectUtil.isNull(userinfo)) {
			userinfo=new UserInfo();
			userinfo.setPhone(phone);
			userinfo.setIsLock("0");
			userinfo.setIsMute("0");
			userinfo.setQq(qq);
			String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
			userinfo.setLoginIp(ip);
			userinfo.setLoginDate(new Date());
			userinfo.setCreateTime(new Date());
			userinfo.setUserId(IdUtil.simpleUUID());
			userinfo.setPassword(SecurityUtils.encryptPassword(password));
			int result=mapper.insert(userinfo);
			if(result==0)
				  throw new ServiceException("用户信息插入失败");
		}else {

			  throw new ServiceException("手机号码已存在");
		}
        
		return userinfo;
	}
	@Override
	public UserInfo findUserInfo(String username) {
		UserInfo userinfo = new LambdaQueryChainWrapper<>(mapper)
				.eq(UserInfo::getPhone, username)
				.one();
		return userinfo;
	}
	
	/**
	 * 校验短信验证码
	 * TODO 简单描述该方法的实现功能（可选）. 
	 * @see com.ruoyi.business.service.IUserServer#validateCode(java.lang.String, java.lang.String)
	 */
	@Override
	public boolean validateCode(String phone, String code) {
		//TODO
		return true;
	}
	@Override
	public boolean vaildateReset(String phone) {
	String key=	redisCache.getCacheObject("accountreset:"+phone);
	if(key!=null)
		
		return false;
	else 
		return true;
	}
	@Override
	public int resetPassword(String phone, String password) {
		UserInfo userinfo = new LambdaQueryChainWrapper<>(mapper)
				.eq(UserInfo::getPhone, phone)
				.one();
		userinfo.setUpdateTime(new Date());
		userinfo.setPassword(SecurityUtils.encryptPassword(password));
		return mapper.updateById(userinfo);
	}

}
